package com.swf.jpa.framework.convert;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.core.MethodParameter;
import org.springframework.util.ClassUtils;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.swf.jpa.framework.constant.MockEnum;
import com.swf.jpa.generator.TableModel;
import com.swf.jpa.model.NotFoundTableModel;
import com.swf.jpa.util.MockUtils;

/**
 * 返回值转换
 *
 * TODO 此部分代码需要优化
 *
 * @author gavin
 * @create 13-7-28
 * @since 1.0.0
 */
public class CommonReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
    	 return ClassUtils.isAssignable(List.class, returnType.getParameterType())||ClassUtils.isAssignable(TableModel.class, returnType.getParameterType());
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
    	String viewName = "";
		if (ClassUtils.isAssignable(List.class, returnType.getParameterType())) {
			MockUtils.setAttribute(
					(HttpServletRequest) webRequest.getNativeRequest(),
					MockEnum.LISTESULT, returnValue);
			viewName = "result/list";
		} else if (ClassUtils.isAssignable(TableModel.class,
				returnType.getParameterType())) {
			if (returnValue != null){
				MockUtils.setAttribute(
					(HttpServletRequest) webRequest.getNativeRequest(),
					MockEnum.SINGLERESULT, returnValue);
			}else{
				MockUtils.setAttribute(
						(HttpServletRequest) webRequest.getNativeRequest(),
						MockEnum.SINGLERESULT, new NotFoundTableModel("0002", "查詢結果為空"));
			}
			viewName = "result/single";
		}
		Boolean isJson = MockUtils.getAttribute((HttpServletRequest) webRequest.getNativeRequest(),MockEnum.ISJSON,Boolean.class);
    	mavContainer.setViewName(viewName+(isJson?"Json":""));
     //   mavContainer.setViewName(null);
     //   mavContainer.setRequestHandled(true);
    }


}
